package com.junzhiit.nengji.cms.web.util.tools;

import java.io.InputStreamReader;
import java.security.KeyPair;
import java.security.PublicKey;
import java.security.Security;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMReader;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

public class KeyUtil {
	
	private static KeyPair keyPair;
	
	private static PublicKey publicKey;
	
	static{
	    if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null){
	        Security.addProvider(new BouncyCastleProvider());
	    }
	}
	
	public static KeyPair keyPair(String privateKeyPath){
		if(keyPair == null){
			keyPair = getKeyPair(privateKeyPath);
		}
		
		return keyPair;
	}
	
	public static PublicKey publicKey(String publicKeyPath){
		if(publicKey == null){
			publicKey = getPublicKey(publicKeyPath);
		}
		return publicKey;
	}
	
	private static KeyPair getKeyPair(String privateKeyPath){
		KeyPair keyPair = null;
		try {
			Resource privateResource = new ClassPathResource(privateKeyPath);
			PEMReader privatePemReader = new PEMReader(new InputStreamReader(privateResource.getInputStream()));
			keyPair = (KeyPair)privatePemReader.readObject();
			if(privatePemReader!=null){
				privatePemReader.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return keyPair;
	}
	
	private static PublicKey getPublicKey(String publicKeyPath){
		PublicKey publicKey= null;
		try {
			Resource PublicResource = new ClassPathResource(publicKeyPath);
			PEMReader publicPemReader = new PEMReader(new InputStreamReader(PublicResource.getInputStream()));
			publicKey = (PublicKey)publicPemReader.readObject();
			if(publicPemReader != null){
				publicPemReader.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return publicKey;
	}
}
